# add run-length column to exist csv files
import os
import csv

# Set the directory containing the CSV files
directory = './search-result'
csv_files = [filename for filename in os.listdir(
    directory) if filename.endswith('.csv')]

flag = False
# Loop through each file in the directory
# for filename in csv_files:
for basename in range(2,26):
    filename = str(basename) + '.csv'
    if filename not in csv_files:
        continue
    header = []
    rows = []
    # Open the file and read its contents
    with open(os.path.join(directory, filename), 'r') as csvfile:
        reader = csv.reader(csvfile)
        header = next(reader)
        for row in reader:
            if len(row) == 0:  # empty row
                continue
            rows.append(row)

    # sort
    sorted_rows = sorted(rows, key=lambda row: int(row[1]) if int(row[1])>0 else -int(row[1]), reverse = True)

    # Write the updated data back to the CSV file
    with open(os.path.join(directory, 'all.csv'), '+a', newline='') as file:
        writer = csv.writer(file)
        if flag == False:
            writer.writerow(header)
            flag = True
        # Write the rows with the new column
        writer.writerows(sorted_rows)
